<?php

class _UrlManager extends CUrlManager
{
	private $_lang = '';

	public function getDefaultLang()
	{
		$lang = Yii::app()->params['defaultLang'];

		return $lang;
	}

	public function getCurrentLang()
	{
		$lang = Yii::app()->language;

		return $lang;
	}

	public function createUrl($route, $params=array(), $ampersand='&')
	{
		$lang = null;
		if(!empty($params['lang']))
		{
			$lang = $params['lang'];
			unset($params['lang']);
		}

		$url = parent::createUrl($route, $params, $ampersand);

		$url = DMultilangHelper::addLangToUrl($url, $lang);

		return $url;
	}

	public function createAbsoluteUrl($route, $params=array(), $ampersand='&')
	{
		exit;
		$lang = null;
		if(!empty($params['lang']))
		{
			$lang = $params['lang'];
			unset($params['lang']);
		}

		$url = parent::createUrl($route, $params, $ampersand);

		$url = DMultilangHelper::addLangToUrl($url, $lang);

		return $url;
	}

	protected function createUrlRule($route,$pattern)
	{
		if(is_array($route) && isset($route['class']))
			return $route;

		$matchLangs = implode('|', array_keys(Yii::app()->params->locales));
//		$matchLangs = '\w{2}';
		if(!$this->_lang)
		{
			$request = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';

			if($request[strlen($request)-1] != '/')
				$request .= '/';

			$matches = array();
			if(mb_eregi('^/('. $matchLangs .')/', $request, $matches) && !empty($matches[0]))
			{
				$matches[0] = trim($matches[0], '/');
				if(!isset(Yii::app()->params->locales[$matches[0]]))
					throw new CHttpException('Language {'. $matches[0] .'} don`t support');

				$_REQUEST['lang'] = $_GET['lang'] = Yii::app()->language = $matches[0];
			}
			else
			{
				$_REQUEST['lang'] = $_GET['lang'] = Yii::app()->language = $this->getDefaultLang();
			}

			$this->_lang = Yii::app()->language;
		}

		return new $this->urlRuleClass($route, $pattern);
	}

	public static function changeLang($lang)
	{
		$request = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';

		if($request[strlen($request)-1] != '/')
			$request .= '/';

		$matchLangs = implode('|', array_keys(Yii::app()->params->locales));

		$matches = array();
		if(mb_eregi('^/('. $matchLangs .')/', $request, $matches) && !empty($matches[0]))
		{
			$request = mberegi_replace('^/\w{2}/',  ($lang == Yii::app()->params['defaultLang'] ? '/' : '/'. $lang.'/'), $request);
		}
		else
		{
			$request = ($lang == Yii::app()->params['defaultLang'] ? '/' : '/'. $lang.'/') . ltrim($request, '/');
		}

		$request = rtrim($request, '/');

		if(empty($request))
			$request = '/';

		return $request;
	}

}